// ws 链接
import msg2Json from './msg2Json'
import config from './config'
import Sig from './sig'
import Cookies from 'js-cookie'
const WsFunc = {
  instance: null,
  init: null,
  error: null,
  onopen: null,
  onmessage: null,
  onclose: null,
  url: null,
  times: 0
}
WsFunc.changeUrl = async function (url, obj) {
  const sigObj = await Sig([obj], config.salt)
  console.log(sigObj.str)
  this.url = `${url}?sig=${sigObj.sig}&${sigObj.str}`
}
WsFunc.init = async function (url, param) {
  let ws
  try {
    await this.changeUrl(url, param)
    ws = new WebSocket(this.url)
    ws.binaryType = 'arraybuffer'
    ws.onopen = () => {
      if (this.onopen) { this.onopen() }
    }
    ws.onmessage = (e) => {
      msg2Json(e.data, (data) => {
        if (this.onmessage) { this.onmessage(data) }
      })
    }
    ws.onclose = (e) => {
      if (this.times >= 5) { return }
      if (this.onclose) { this.onclose(e) }
    }
    ws.error = (e) => {
      this.times += 1
      ws.close()
      if (this.error) { this.error(e) }
    }
    this.instance = ws
  }
  catch (error) {
    console.log(error)
  }
}
export default WsFunc
